<script setup>
import icon from '../imgs/imageUploadIcon.svg'
import deleteIcon from '../imgs/deleteBtn.svg'
import { postUploadFile } from '@/axios/api/upload'
import { defineExpose, useSlots } from 'vue'

const props = defineProps({
  customPreviewImg: {
    type: Boolean,
    default: false,
  },
  width: {
    type: String,
    default: '120px',
  },
  height: {
    type: String,
    default: '120px',
  },
  maxCount: {
    type: Number,
    default: 9,
  },
  title: {
    type: String,
    default: '上传图片',
  },
  values: {
    type: String,
    default: '',
  },
})

const slots = useSlots()
const hasSlot = computed(() => !!slots.default)

const previewImgs = ref([]) //预览图片Base64数组
const uploadImgs = ref([]) //上传图片FormData数组

const currentImgCount = computed(() => previewImgs.value.length)

onMounted(() => {
  nextTick(() => {
    if (props.values) {
      previewImgs.value = [props.values]
    }
  })
})

const handleUpload = () => {
  const fileInput = document.getElementById('lfImgUpload')
  fileInput.click()
}

const readAndUploadFile = (event) => {
  const files = event.target.files

  console.log('files', event.target)
  console.log('files', event.target.files)
  console.log('files', event.target.files[0])

  if (files.length > props.maxCount - currentImgCount.value) {
    // error.textContent = `最多只能选择 ${MAX_IMAGE_COUNT} 个文件`
    // fileInput.value = '' // 清空已选文件
    alert(`最多只能选择 ${props.maxCount} 个文件`)
  } else {
    // error.textContent = ''

    Array.from(files).forEach((file) => {
      uploadImgs.value.push(file)
      console.log('uploadImgs.value', uploadImgs.value)

      const reader = new FileReader()

      // 监听文件读取完成事件
      reader.onload = function (event) {
        previewImgs.value.push(event.target.result) // 添加到预览数组
      }

      // 读取文件为Base64字符串
      reader.readAsDataURL(file)
    })
  }
}

const deletePreviewImg = (index) => {
  previewImgs.value.splice(index, 1)
  uploadImgs.value.splice(index, 1)
}

const uploadImg = (onAllUploadsComplete) => {
  if (uploadImgs.value.length == previewImgs.value.length) {
    const formDataList = uploadImgs.value.map((file) => {
      const formData = new FormData()
      formData.append('Image', file)
      return formData
    })

    // 创建一个包含所有请求的 Promise 数组
    const uploadPromises = formDataList.map((formData) => postUploadFile(formData))

    // 等所有请求完成后执行下一步
    Promise.all(uploadPromises)
      .then((responses) => {
        // console.log('所有图片上传成功:', responses)
        // 处理成功后的逻辑
        const imgUrls = responses.map((response) => response.result)
        onAllUploadsComplete(imgUrls) // 调用传入的回调函数
      })
      .catch((error) => {
        console.error('某个请求失败:', error)
        // 处理错误逻辑
      })
  } else {
    onAllUploadsComplete(previewImgs.value)
  }
}

defineExpose({
  deletePreviewImg,
  uploadImg,
  handleUpload,
  uploadImgs,
  previewImgs,
})
</script>

<template>
  <div class="flex gap-3">
    <!-- 上传图片预览 -->
    <div v-if="previewImgs.length > 0 && !customPreviewImg" class="flex gap-2">
      <div v-for="(item, index) in previewImgs" class="relative w-fit">
        <button @click="deletePreviewImg(index)" class="absolute top-1 right-1 w-4 h-4 opacity-50">
          <img :src="deleteIcon" alt="" />
        </button>
        <img :style="{ width: props.width, height: props.height }" class="rounded-lg object-cover" :src="item" alt="" />
      </div>
    </div>

    <div class="flex items-center">
      <input type="file" :onchange="readAndUploadFile" id="lfImgUpload" accept="image/*" multiple />
      <div v-if="hasSlot" class="flex-cc">
        <slot />
      </div>
      <button
        v-if="currentImgCount < props.maxCount && !hasSlot"
        @click="handleUpload"
        :style="{ width: props.width, height: props.height }"
        class="bg-slate-300 rounded-lg flex-cc cursor-pointer flex-col gap-2">
        <img :src="icon" alt="" class="w-8 h-8" />
        <span class="text-sm text-[--text-0]">{{ props.title }}</span>
      </button>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
